<template>
  <div class="add-container">
    <!-- 面包屑部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="margin-top">
      <!-- 提示信息 -->
      <el-alert
        title="消息提示的文案"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="parseInt(activeIndex)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="goodsCatProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabData"
              :key="item.attr_id"
            >
              <!-- 多选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item1"
                  v-for="(item1, index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="successHandor"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本框 -->
            <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor">
            </quill-editor>
            <!-- 提交商品按钮 -->
            <el-button type="primary" class="margin-top" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog
      title="图片预览"
      :visible.sync="imgPreviosdialogVisible"
      width="50%"
    >
      <img :src="previosImg" style="width: 100%" alt="" />
    </el-dialog>
  </div>
</template>

<script>
// 导入getAllCateListAPI接口
import { getAllCateListAPI } from '@/api/getAllCateListAPI.js'
// 导入getCateGoriesAPI接口
import { getCateGoriesAPI } from '@/api/getCateGoriesAPI.js'

// 导入lodash
import _ from 'lodash'

// 导入addGoodsAPI接口
import { addGoodsAPI } from '@/api/addGoodsAPI.js'
export default {
  name: 'Add',
  data() {
    return {
      // 步骤条与tab侧边栏的对应关系
      activeIndex: '0',
      // 添加商品的表单数据对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品分类的分类id
        goods_cat: [],
        // 图片的临时地址列表
        pics: [],
        // 商品介绍
        goods_introduce: '',
        // 商品的参数，动态参数和静态属性的数组
        attrs: []
      },
      // 添加商品的表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [{ required: true, message: '请选择商品分类' }]
      },
      // 商品分类数据列表
      cateList: [],
      // 级联下拉菜单的配置选项
      goodsCatProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        checkStrictly: 'true'
      },
      // 商品参数列表
      manyTabData: [],
      // 商品属性列表
      onlyTabData: [],
      // 上传图片的请求头headers配置
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 控制图片预览对话框显示隐藏
      imgPreviosdialogVisible: false,
      // 图片预览的url地址
      previosImg: ''
    }
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await getAllCateListAPI()
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据列表失败')
      }
      // console.log(res.data)
      this.cateList = res.data
      console.log(this.cateList)
    },
    // 当级联下拉菜单的值发生变化就会触发该事件处理函数handleChange
    handleChange() {
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 阻止标签跳转
    beforeLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 监听tabs点击事件处理函数
    async tabClick() {
      console.log(this.cateId)
      if (this.activeIndex === '1') {
        const { data: res } = await getCateGoriesAPI(this.cateId, 'many')
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数失败')
        }
        console.log(res.data)
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyTabData = res.data
        console.log(this.manyTabData)
      } else if (this.activeIndex === '2') {
        const { data: res } = await getCateGoriesAPI(this.cateId, 'only')
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        }
        this.onlyTabData = res.data
        this.$message.success(res.meta.msg)
      }
    },
    // 点击图片预览的操作处理函数
    handlePreview(file) {
      console.log(file.response.data.url)
      this.previosImg = file.response.data.url
      this.imgPreviosdialogVisible = true
    },
    // 点击删除图片的处理函数
    handleRemove(file) {
      console.log(file.response.data.tmp_path)
      const picpath = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex((item) => {
        // 返回的是一个对应元素的下标
        return item.pic === picpath
      })
      // splice(删除元素开始位置的index,要删除的个数)
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm)
    },
    // 图片上传成功时执行的函数
    successHandor(response) {
      console.log(response)
      const picInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(picInfo)
      console.log(this.addForm)
    },
    // 添加商品
    add() {
      // 添加之前先进行表单的预校验
      this.$refs.addFormRef.validate(async(valid) => {
        if (!valid) {
          return this.$message.error('请填写必要的表单信息!')
        }
        // 执行添加表单的业务逻辑
        // 把addForm的商品分类的id数组转换成字符串
        const cloneForm = _.cloneDeep(this.addForm)
        cloneForm.goods_cat = cloneForm.goods_cat.join(',')
        console.log(cloneForm)
        // console.log(this.addForm)
        // console.log(this.manyTabData)
        this.manyTabData.forEach((item) => {
          const manyAttrsInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(manyAttrsInfo)
        })
        // console.log(this.addForm.attrs)
        console.log(this.onlyTabData)
        this.onlyTabData.forEach((item) => {
          const onlyAttrsInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(onlyAttrsInfo)
        })
        cloneForm.attrs = this.addForm.attrs
        console.log(cloneForm)
        const { data: res } = await addGoodsAPI(cloneForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        this.$router.push('/home/goods')
      })
    }
  },
  // 计算属性，把属性进行一些处理后再拿来用
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
      }
      return false
    }
  },
  created() {
    this.getCateList()
  }
}
</script>

<style lang="less" scoped>
.margin-top {
  margin-top: 15px;
}

.el-steps {
  margin: 15px 0;
}

/deep/.el-step__title {
  font-size: 12px !important;
}

.el-checkbox {
  margin: 0 10px 0 0 !important;
}

/deep/.ql-editor {
  height: 400px;
}
</style>
